package com.android.djlmapp.tools.read;

import android.app.Activity;
import android.os.Handler;
import android.util.Log;

import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.listener.read.GetImsiListener;
import com.android.djlmapp.listener.read.GetPhotoUrlListener;
import com.android.djlmapp.listener.read.GetWriteCardDataListener;
import com.android.djlmapp.model.home.Info;
import com.android.djlmapp.model.readcard.WriteImsiInfo;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.readcard.bean.WritePhoneNumInfo;
import com.android.readcard.dialog.YqDialog;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

public class WriteCardUtils {

    /**
     * 提示消息,四秒后自动关闭
     *
     * @param result
     * @param result
     */
    public static void showMsg(Activity activity, String title, String result) {
        YqDialog yqDialog = new YqDialog(activity);
        yqDialog.setCancelable(true);

        yqDialog.setTitle(title);
        yqDialog.setStr(result);
        yqDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                yqDialog.cancel();
            }
        }, 3000);
    }


    /**
     * 写卡成功,上传数据
     *
     * @param sucUrl
     * @param iccidNum
     * @param orderSn
     * @param xieOrBu
     */
    public static void writeSucSubmit(Activity activity, String sucUrl, String iccidNum,
                               String orderSn, String xieOrBu, GetPhotoUrlListener mGetPhotoUrlListener) {
        subWriteSuc(sucUrl, xieOrBu, orderSn, iccidNum, new GetPhotoUrlListener() {
            @Override
            public void backPhotoUrl(int backType, String msg) {
                Log.e("项目异常写卡", backType + "------startWrite---backErr---" + sucUrl);
                // 写卡完成,成功失败都要提示并且关闭写卡界面
                if (mGetPhotoUrlListener != null) {
                    mGetPhotoUrlListener.backPhotoUrl(backType, "");
                }
                Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
                EventBusUtil.sendEvent(clearCardEvent);
                showMsg(activity, xieOrBu + "结果", msg);

            }
        });
    }

    /**
     * 获取短信中心号和imsi
     *
     * @param mUrl
     * @param iccidNum
     * @param orderSn
     * @param xieOrBu  补卡还是写卡
     */
    public static void startWrite(Activity activity, String mUrl, String iccidNum, String orderSn,
                                  String xieOrBu) {
        startWriteCard(mUrl, iccidNum, orderSn, new GetWriteCardDataListener() {
            @Override
            public void backSuc(String mPhoneNum, String mImsi) {
                Log.e("项目异常写卡", xieOrBu + "------startWrite---backSuc---" + mUrl);


                WritePhoneNumInfo writePhoneNumInfo = new WritePhoneNumInfo();
                writePhoneNumInfo.setPhoneNum(mPhoneNum);
                writePhoneNumInfo.setImsi(mImsi);
                writePhoneNumInfo.setErr("");
                // 返回短信中心号和imsi
                Event<WritePhoneNumInfo> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.C, writePhoneNumInfo);
                EventBusUtil.sendEvent(clearCardEvent);
            }

            @Override
            public void backErr(String err) {
                Log.e("项目异常写卡", err + "------startWrite---backErr---" + mUrl);

                // 获取短信中心号失败
                WritePhoneNumInfo writePhoneNumInfo = new WritePhoneNumInfo();
                writePhoneNumInfo.setPhoneNum("");
                writePhoneNumInfo.setImsi("");
                writePhoneNumInfo.setErr(err);
                // 返回短信中心号和imsi
                Event<WritePhoneNumInfo> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.C, writePhoneNumInfo);
                EventBusUtil.sendEvent(clearCardEvent);
                showMsg(activity, xieOrBu + "结果", err);
            }
        });
    }

    /**
     * 废卡重置
     *
     * @param iccid
     * @param imsi
     * @param mGetPhotoUrlListener
     */
    public static void clearCard(String iccid, String imsi, GetPhotoUrlListener mGetPhotoUrlListener) {
        MyApplication.getInstance().getHttpTools().clearCard(iccid, imsi, new StringCallback() {

            @Override
            public void onSuccess(Response<String> response) {
                Log.e("项目异常写卡", "----废卡重置结果----" + response.body());
                try {
                    JSONObject json = new JSONObject(response.body());
                    int code = json.getInt("code");
                    String result = "";
                    switch (code) {
                        case 3101: // 返回读取失败
                            result = "重置失败:" + json.getString("msg");
                            break;
                        case 3102: // 返回false
                            result = "重置失败:" + json.get("msg");
                            if (result.contains("卡片已置为可用状态")) {
                                result = "重置成功";
                            }
                            break;
                        case 200: // 重置成功
                            result = json.getString("msg");
                            // 成功的返回码是啥
                            break;
                    }
                    mGetPhotoUrlListener.backPhotoUrl(1, result);
                } catch (JSONException e) {
                    e.printStackTrace();
                    mGetPhotoUrlListener.backPhotoUrl(2, "数据解析异常");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                mGetPhotoUrlListener.backPhotoUrl(2, "网络或服务器错误");
            }
        });
    }

    /**
     * 获取短信中心号和imsi
     *
     * @param url
     * @param oneValue
     * @param twoValue
     * @param mGetWriteCardDataListener
     */
    private static void startWriteCard(String url, String oneValue, String twoValue,
                                       GetWriteCardDataListener mGetWriteCardDataListener) {
        MyApplication.getInstance().getHttpTools().startWriteCard(url, oneValue,
                twoValue, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("项目异常写卡", "----获取短信中心号----" + response.body());
                        try {
                            if (response.body().contains("status")) {
                                JSONObject json = new JSONObject(response.body());
                                String status = json.getString("status");
                                if ("1".equals(status)) {
                                    // 成功
                                    JSONObject msg = json.getJSONObject("msg");

                                    String Send_number = msg.getString("send_number");
                                    String IMSI = msg.getString("imsi");
                                    mGetWriteCardDataListener.backSuc(Send_number, IMSI);
                                } else {
                                    // 失败
                                    String msg = json.getString("msg");
                                    mGetWriteCardDataListener.backErr(msg);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e("项目异常写卡", "----获取短信中心号解析异常----" + response.body());
                            mGetWriteCardDataListener.backErr("获取短信中心号异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("项目异常写卡", "----获取短信中心号网络错误----" + response.body());
                        mGetWriteCardDataListener.backErr("获取短信中心号错误");
                    }
                });
    }

    /**
     * 设备写卡成功,提交数据到服务器
     *
     * @param url
     * @param orderSn
     * @param iccid
     */
    private static void subWriteSuc(String url, String xieOrBu, String orderSn, String iccid,
                                    GetPhotoUrlListener mGetPhotoUrlListener) {
        MyApplication.getInstance().getHttpTools().subWriteSuc(url, orderSn, iccid, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.e("项目异常写卡", "----写卡成功----" + response.body());
                try {
                    if (response.body().contains("status")) {
                        JSONObject json = new JSONObject(response.body());
                        String status = json.getString("status");
                        if ("1".equals(status)) {
                            mGetPhotoUrlListener.backPhotoUrl(1, xieOrBu + "成功");
                        } else {
                            String msg = json.getString("msg");
                            mGetPhotoUrlListener.backPhotoUrl(2, msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mGetPhotoUrlListener.backPhotoUrl(2, "写卡解析异常");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                mGetPhotoUrlListener.backPhotoUrl(2, "写卡网络错误");
            }
        });
    }


    public static void getKuanDaiImsi(Activity activity, String iccid, String phonenum, String idcard) {
        kuanDaiGetImsi(iccid, phonenum, idcard, new GetImsiListener() {
            @Override
            public void backSuc(WriteImsiInfo.DataBean info) {
                Log.e("项目异常写卡", "------getKuanDaiImsi--" + info.toString());

                WritePhoneNumInfo writePhoneNumInfo = new WritePhoneNumInfo();
                writePhoneNumInfo.setPhoneNum(info.getSend_number());
                writePhoneNumInfo.setImsi(info.getImsi());

                PrefUtils.putString(ConstantsValue.WRITE_KD_IDCARD, idcard);
                PrefUtils.putString(ConstantsValue.WRITE_KD_ICCID, iccid);
                PrefUtils.putString(ConstantsValue.WRITE_KD_PHONE, phonenum);
                PrefUtils.putString(ConstantsValue.WRITE_KD_IMSI, info.getImsi());
                PrefUtils.putString(ConstantsValue.WRITE_KD_PROCID, info.getProcid());
                PrefUtils.putString(ConstantsValue.WRITE_KD_EMPTY, info.getEmptyCardId());
                PrefUtils.putString(ConstantsValue.WRITE_KD_CARD_DATA, info.getCardData());


                writePhoneNumInfo.setErr("");
                // 返回短信中心号和imsi
                Event<WritePhoneNumInfo> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.C, writePhoneNumInfo);
                EventBusUtil.sendEvent(clearCardEvent);
            }

            @Override
            public void backErr(String err) {
                Log.e("项目异常写卡", "-----getKuanDaiImsi--backErr---" + err);

                // 获取短信中心号失败
                WritePhoneNumInfo writePhoneNumInfo = new WritePhoneNumInfo();
                writePhoneNumInfo.setPhoneNum("");
                writePhoneNumInfo.setImsi("");
                writePhoneNumInfo.setErr(err);
                // 返回短信中心号和imsi
                Event<WritePhoneNumInfo> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.C, writePhoneNumInfo);
                EventBusUtil.sendEvent(clearCardEvent);
                showMsg(activity, "写卡结果", err);
            }
        });
    }


    /**
     * 宽带获取IMSI
     *
     * @param iccid
     * @param phonenum
     * @param idcard
     */
    private static void kuanDaiGetImsi(String iccid, String phonenum, String idcard,
                                       GetImsiListener mGetWriteCardDataListener) {

        MyApplication.getInstance().getHttpTools().getKuanDaiImsi(iccid, phonenum,
                idcard, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            Gson gson = new Gson();
                            WriteImsiInfo writeImsiInfo = gson.fromJson(response.body(), WriteImsiInfo.class);
                            if (writeImsiInfo.getCode() == 200) {
                                mGetWriteCardDataListener.backSuc(writeImsiInfo.getData());
                            } else {
                                mGetWriteCardDataListener.backErr(writeImsiInfo.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            mGetWriteCardDataListener.backErr("获取短信中心号异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mGetWriteCardDataListener.backErr("获取短信中心号错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 提交宽带写卡结果
     *
     * @param activity
     * @return // 返回值可以用来判断宽带写卡成功数量
     */
    public static boolean subKuanDaiWrite(Activity activity) {
        String iccid = PrefUtils.getString(ConstantsValue.WRITE_KD_IDCARD, "");
        String idcard = PrefUtils.getString(ConstantsValue.WRITE_KD_ICCID, "");
        String phonenum = PrefUtils.getString(ConstantsValue.WRITE_KD_PHONE, "");
        String imsi = PrefUtils.getString(ConstantsValue.WRITE_KD_IMSI, "");
        String procid = PrefUtils.getString(ConstantsValue.WRITE_KD_PROCID, "");
        String emptyCardId = PrefUtils.getString(ConstantsValue.WRITE_KD_EMPTY, "");
        String cardData = PrefUtils.getString(ConstantsValue.WRITE_KD_CARD_DATA, "");

        final boolean[] isRefWeb = {false};
        kuanDaiWriteCard(phonenum, idcard, procid, emptyCardId, imsi, cardData, iccid,
                new GetPhotoUrlListener() {
                    @Override
                    public void backPhotoUrl(int backType, String msg) {
                        Log.e("项目异常写卡", backType + "------subKuanDaiWrite---" + msg);
                        // 写卡完成,成功失败都要提示并且关闭写卡界面
                        Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
                        EventBusUtil.sendEvent(clearCardEvent);
                        showMsg(activity, "写卡结果", msg);
                        if (backType == 1) {
                            // TODO 如果是订单web页要刷新可以在这里刷新
                            isRefWeb[0] = true;
                        } else {
                            isRefWeb[0] = false;
                        }
                    }
                });
        return isRefWeb[0];
    }


    /**
     * 宽带提交写卡成功
     *
     * @param phonenum
     * @param idcard
     * @param procid
     * @param emptyCardId
     * @param imsi
     * @param cardData
     * @param iccid_no
     */
    private static void kuanDaiWriteCard(String phonenum, String idcard, String procid,
                                         String emptyCardId, String imsi, String cardData,
                                         String iccid_no, GetPhotoUrlListener mGetPhotoUrlListener) {
        MyApplication.getInstance().getHttpTools().subKuanDaiWriteCard(phonenum, idcard, procid,
                emptyCardId, imsi, cardData, iccid_no, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("项目异常写卡", "----写卡成功----" + response.body());
                        try {
                            Gson gson = new Gson();
                            Info info = gson.fromJson(response.body(), Info.class);
                            if (info.getCode() == 200) {
                                mGetPhotoUrlListener.backPhotoUrl(1, "写卡成功"); // 成功
                            } else {
                                mGetPhotoUrlListener.backPhotoUrl(2, info.getMsg()); // 失败
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            mGetPhotoUrlListener.backPhotoUrl(2, "写卡解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mGetPhotoUrlListener.backPhotoUrl(2, "写卡网络错误");
                    }
                });
    }
}
